<script setup lang="ts">
import request from "@/utils/request";
import API from "@/api";
let queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: "",
  total: 0,
});

let tableData = ref([]);
let tableLoading = ref(false);
const tableRef = toRef();

onMounted(() => {
  queryList();
});
const queryList = async () => {
  try {
    tableLoading.value = true;
    const res = await request.get(API.pageDishQuery, {
      params: queryParams,
    });
    if (res.code === 1) {
      tableData.value = res.data.records || [];
      queryParams.total = res.data.total || 0;
    }
  } catch (error) {
    ElMessage.error("获取数据失败!");
  } finally {
    tableLoading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  queryList();
};
// 分页
const handleSizeChange = (val: number) => {
  queryParams.page = 1;
  queryParams.pageSize = val;
  queryList();
};
const handleCurrentChange = (val: number) => {
  queryParams.page = val;
  queryList();
};

const priceFormatter = (row: { price: number }): string => {
  return `$ ${row.price / 100}`;
};
const statusFormatter = (row: { status: number }): string => {
  return row.status ? "停售" : "启售";
};

const getImage = (image: string) => {
  const APP_SERVER_URL = import.meta.env.VITE_APP_SERVER_URL;
  return `${APP_SERVER_URL}/common/download?name=${image}`;
};

type StatusType = {
  id: string;
  status: string;
};

const singleStatusEdit = (row: StatusType) => {
  ElMessageBox.confirm("确认更改该菜品状态吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    console.log("row.status", row.status);
    const params = {
      id: row.id,
      status: row.status === 0 ? 1 : 0,
    };
    request.put(API.editDish, params).then((res) => {
      if (res.code === 1) {
        ElMessage.success("菜品状态已经更改成功!");
        handleQuery();
      } else {
        ElMessage.error("菜品状态更改失败!");
      }
    });
  });
};

// 删除
const onBatchDelete = () => {
  const ids = tableRef.value.getSelectionRows().map((item: object) => item.id);
  if (ids.length === 0) {
    ElMessage.warning("请选择要删除的菜品!");
    return;
  }
  deleteRowRequest(ids);
};
const deleteItem = async (id: string) => {
  deleteRowRequest([id]);
};

const deleteRowRequest = (ids: string[]) => {
  ElMessageBox.confirm("确认删除选中菜品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await request.delete(API.deleteDish, {
      data: ids,
    });
    if (res.code === 1) {
      ElMessage.success("菜品删除成功!");
      handleQuery();
    } else {
      ElMessage.error("菜品删除失败!");
    }
  });
};
const addDishItem = () => {};

const addFoodType = (row: Record<string, any> | string) => {
  console.log("row", row);
};
</script>

<template>
  <page-view>
    <template #tableBar>
      <section class="w-full flex justify-between">
        <section class="w-240 inline-block">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入菜品名称"
            clearable
            @clear="handleQuery"
            @keyup.enter.native="handleQuery"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <i-ep-search />
              </el-icon>
            </template>
          </el-input>
        </section>
        <section>
          <el-button type="danger" @click="onBatchDelete">批量删除</el-button>
          <el-button type="primary" @click="addDishItem">+ 新建菜品</el-button>
        </section>
      </section>
    </template>
    <el-table
      :data="tableData"
      ref="tableRef"
      stripe
      v-loading="tableLoading"
      height="600"
      :border="true"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="70" label="序号" align="center" />
      <el-table-column prop="name" label="菜品名称" />
      <el-table-column prop="image" label="图片" align="center">
        <template #default="{ row }">
          <el-image
            :src="getImage(row.image)"
            fit="fill"
            :preview-src-list="[getImage(row.image)]"
            :preview-teleported="true"
            class="h-40 w-auto"
          >
            <template #error>
              <section class="font-size-30">
                <el-icon><i-ep-picture /></el-icon>
              </section>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="菜品分类" />
      <el-table-column prop="price" label="售价" :formatter="priceFormatter" />
      <el-table-column
        prop="status"
        label="售卖状态"
        :formatter="statusFormatter"
      />
      <el-table-column prop="updateTime" label="最后操作时间" />
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button
            link
            size="small"
            type="primary"
            @click="addFoodType(scope.row)"
          >
            修改
          </el-button>
          <el-button
            link
            size="small"
            type="primary"
            @click="singleStatusEdit(scope.row)"
          >
            {{ scope.row.status ? "启售" : "停售" }}
          </el-button>
          <el-button
            link
            size="small"
            type="danger"
            @click="deleteItem(scope.row?.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="justify-center mt-10"
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="queryParams.total"
      :hide-on-single-page="queryParams.total === 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </page-view>
</template>
